package com.lz.ccjdemo.http;

import com.lz.ccjdemo.App;
import com.lz.ccjdemo.http.api.BaseApiService;
import com.lz.ccjdemo.http.gson.GsonAdapter;
import com.lz.ccjdemo.http.interceptor.HeadInterceptor;

import java.io.File;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.BiFunction;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class HttpUtils {

    private final long cacheLength = 1024 * 1024 * 100;
    private final long CONNECT_TIMEOUT = 60;  //网络请求设置超时时长
    public Retrofit retrofit;
    public BaseApiService apiService;
    public static HttpUtils api;

    private boolean IS_SHOW_LOG=true;


    private HttpUtils() {
        //日志log
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        //正式环境因该设置不打印日志
        httpLoggingInterceptor.setLevel(IS_SHOW_LOG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);

        //缓存
        File cacheFile = new File(App.getApp().getCacheDir(), "cache");
        Cache cache = new Cache(cacheFile, cacheLength); //100Mb
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        OkHttpClient okHttpClient = builder
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .addInterceptor(new HeadInterceptor())//增加头部拦截
                .addInterceptor(httpLoggingInterceptor)//增加日志Log打印
                .cache(cache).build();

        retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(GsonAdapter.buildGson()))
                .baseUrl(HttpConfig.getConfig().getHost())
                .build();

        apiService = retrofit.create(BaseApiService.class);
    }

    /**
     * 获取ApiService
     *
     * @return
     */
    public static BaseApiService getDefault() {
        if (api == null)
            api = new HttpUtils();
        return api.apiService;
    }


    //单接口请求
    public static <T> Observable<T> observe(Observable<T> observable) {
        return observable
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    //合并接口请求
    public static <T, U> Observable<CombinedResult<T, U>> observe(Observable<T> observable, Observable<U> observable1) {
        return Observable.zip(observable, observable1,
                        new BiFunction<T, U, CombinedResult<T, U>>() {
                            @Override
                            public CombinedResult<T, U> apply(T t, U u) throws Exception {
                                return new CombinedResult<>(t, u);
                            }
                        })
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }
}
